package com.jiawa.train.business.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jiawa.train.business.domain.DailyTrain;
import com.jiawa.train.business.domain.DailyTrainExample;
import com.jiawa.train.business.domain.Train;
import com.jiawa.train.business.mapper.DailyTrainMapper;
import com.jiawa.train.business.req.DailyTrainQueryReq;
import com.jiawa.train.business.req.DailyTrainSaveReq;
import com.jiawa.train.business.resp.DailyTrainQueryResp;
import com.jiawa.train.business.service.*;
import com.jiawa.train.common.exception.BusinessException;
import com.jiawa.train.common.exception.BusinessExceptionEnum;
import com.jiawa.train.common.resp.PageResp;
import com.jiawa.train.common.util.SnowUtil;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author zzl
 * @version 1.0
 */
@Service
public class DailyTrainServiceImpl implements DailyTrainService {
    private static final Logger LOG = LoggerFactory.getLogger(DailyTrainServiceImpl.class);

    @Resource
    private DailyTrainMapper dailyTrainMapper;
    @Resource
    private TrainService trainService;
    @Resource
    private DailyTrainStationService dailyTrainStationService;
    @Resource
    private DailyTrainCarriageService dailyTrainCarriageService;
    @Resource
    private DailyTrainSeatService dailyTrainSeatService;
    @Resource
    private DailyTrainTicketService dailyTrainTicketService;
    @Resource
    private SkTokenService skTokenService;

    @Override
    public void save(DailyTrainSaveReq req) {
        DateTime now = DateTime.now();
        DailyTrain dailyTrain = BeanUtil.copyProperties(req, DailyTrain.class);
        if(ObjectUtil.isNull(dailyTrain.getId())) {
            if(isExist(dailyTrain)) {
                throw new BusinessException(BusinessExceptionEnum.TRAIN_IS_EXIST);
            } else {
                dailyTrain.setId(SnowUtil.getSnowflakeNextId());
                dailyTrain.setCreateTime(now);
                dailyTrain.setUpdateTime(now);
                dailyTrainMapper.insert(dailyTrain);
            }
        } else {
            dailyTrain.setUpdateTime(now);
            dailyTrainMapper.updateByPrimaryKeySelective(dailyTrain);
        }
    }

    /**
     * 分页查询每日高铁数据
     * @param req
     * @return
     */
    @Override
    public PageResp<DailyTrainQueryResp> queryList(DailyTrainQueryReq req) {
        DailyTrainExample dailyTrainExample = new DailyTrainExample();
        dailyTrainExample.setOrderByClause("date asc, code asc");
        DailyTrainExample.Criteria criteria = dailyTrainExample.createCriteria();
        if(ObjectUtil.isNotNull(req.getDate())) {
            criteria.andDateEqualTo(req.getDate());
        }
        if(ObjectUtil.isNotNull(req.getCode())) {
            criteria.andCodeEqualTo(req.getCode());
        }

        LOG.info("查询页码：{}", req.getPage());
        LOG.info("每页条数：{}", req.getSize());
        PageHelper.startPage(req.getPage(), req.getSize());
        List<DailyTrain> dailyTrainList = dailyTrainMapper.selectByExample(dailyTrainExample);

        PageInfo<DailyTrain> pageInfo = new PageInfo<>(dailyTrainList);
        LOG.info("总行数：{}", pageInfo.getTotal());
        LOG.info("总页数：{}", pageInfo.getPages());

        List<DailyTrainQueryResp> dailyTrainQueryRespList = BeanUtil.copyToList(dailyTrainList, DailyTrainQueryResp.class);

        PageResp<DailyTrainQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(dailyTrainQueryRespList);

        return pageResp;
    }

    @Override
    public void delete(Long id) {
        dailyTrainMapper.deleteByPrimaryKey(id);
    }

    /**
     * 根据日期生成每日高铁数据
     * @param date
     */
    @Override
    public void genDaily(Date date) {
        // 查询所有高铁车次
        List<Train> trainList = trainService.selectAll();
        if(CollUtil.isEmpty(trainList)) {
            LOG.info("火车车次基础数据为空");
            return;
        }

        // 遍历所有高铁车次，逐个生成车次的每日数据
        for(Train train : trainList) {
            genDailyTrain(date, train);
        }
    }

    /**
     * 根据日期和车次，生成每日高铁数据
     * @param date
     * @param train
     */
    @Transactional
    public void genDailyTrain(Date date, Train train) {
        LOG.info("生成日期【{}】车次【{}】的信息开始", DateUtil.formatDate(date), train.getCode());
        DailyTrainExample dailyTrainExample = new DailyTrainExample();
        dailyTrainExample.createCriteria()
                .andDateEqualTo(date)
                .andCodeEqualTo(train.getCode());
        // 1.删除每日高铁数据
        dailyTrainMapper.deleteByExample(dailyTrainExample);

        // 2.插入每日高铁数据
        DateTime now = DateTime.now();
        DailyTrain dailyTrain = BeanUtil.copyProperties(train, DailyTrain.class);
        dailyTrain.setId(SnowUtil.getSnowflakeNextId());
        dailyTrain.setDate(date);
        dailyTrain.setCreateTime(now);
        dailyTrain.setUpdateTime(now);
        dailyTrainMapper.insert(dailyTrain);

        // 3.生成每日高铁经停站、每日高铁车厢、每日高铁座位、每日高铁票、令牌
        dailyTrainStationService.genDailyTrainStation(date, train);
        dailyTrainCarriageService.genDailyTrainCarriage(date, train);
        dailyTrainSeatService.genDailyTrainSeat(date, train);
        dailyTrainTicketService.genDailyTrainTicket(date, dailyTrain);
        skTokenService.genDaily(date, dailyTrain);

        LOG.info("生成日期【{}】车次【{}】的信息结束", DateUtil.formatDate(date), train.getCode());
    }

    /**
     * 判断每日车次数据是否存在
     * @param dailyTrain
     * @return
     */
    private boolean isExist(DailyTrain dailyTrain) {
        DailyTrainExample dailyTrainExample = new DailyTrainExample();
        dailyTrainExample.createCriteria()
                .andDateEqualTo(dailyTrain.getDate())
                .andCodeEqualTo(dailyTrain.getCode());
        List<DailyTrain> list = dailyTrainMapper.selectByExample(dailyTrainExample);
        if(CollUtil.isNotEmpty(list)) return true;
        else return false;
    }
}
